# -*- coding: utf-8 -*-

'''
评论管理函数
'''
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
import pandas as pd
import uuid
import datetime
import re
import hashlib
from ...pao_python.pao.service.security.security_service import RoleService
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...service.common import find_data, update_data, delete_data, get_condition, get_info, get_current_user_id
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.mongo_bill_service import MongoBillFilter


class CommentManageService(MongoService):
    ''' 评论管理服务 '''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.role_service = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_comment_list(self, order_ids, condition, page, count):
        '''获取评论管理列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'comment_object_id', 'type_id', 'level',
                'comment_user_id', 'start_date', 'end_date']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_Comment_Type', 'type_id', 'id', 'type')\
            .lookup_bill('PT_User', 'comment_user_id', 'id', 'comment_user')\
            .add_fields({
                'type': '$type.name',
                'comment_user': '$comment_user.name'
            })\
            .match_bill((C('id') == values['id'])
                        & (C('organization_id').inner(order_ids))
                        & (C('comment_date') >= as_date(values['start_date']))
                        & (C('comment_date') <= as_date(values['end_date']))
                        & (C('type_id') == values['type_id'])
                        & (C('comment_user_id') == values['comment_user_id'])
                        & (C('comment_object_id') == values['comment_object_id'])
                        & (C('level').like(values['level'])))\
            .project({'_id': 0, 'type._id': 0})
        res = self.page_query(_filter, 'PT_Comment', page, count)
        # for key,result in enumerate(res.get('result')):
        #     comment_object_id = result.get('comment_object_id')
        #     _filter_obj = MongoFilter()
        #     # result['issue_date'] = date_format(result.get('issue_date'))
        #     _filter_obj.match((C('bill_status') == 'valid') &(C('id') == comment_object_id)).project({'_id': 0})
        #     if len(self.page_query(_filter_obj, 'PT_Service_Item', page, count)['result'])>0:
        #         _filter_obj.match(C('name').like(values['comment_object_id']))
        #         res_obj = self.page_query(_filter_obj, 'PT_Service_Item', page, count)
        #         if res_obj['result']:
        #             result['comment_object'] = '服务项目-'+ res_obj['result'][0].get('name')
        #         else:
        #             res.get('result').pop(key)
        #             res['total'] =int(res.get('total')) - 1
        #     elif len(self.page_query(_filter_obj, 'PT_Article', page, count)['result'])>0:
        #         # print('111',self.page_query(_filter_obj, 'PT_Article', page, count)['result'])
        #         _filter_obj.match(C('title').like(values['comment_object_id']))
        #         res_obj = self.page_query(_filter_obj, 'PT_Article', page, count)
        #         if res_obj['result']:
        #             result['comment_object'] = '文章-'+ res_obj['result'][0].get('title')
        #         else:
        #             res.get('result').pop(key)
        #             res['total'] =int(res.get('total')) - 1
        #     elif len(self.page_query(_filter_obj, 'PT_Activity', page, count)['result'])>0:
        #         _filter_obj.match(C('activity_name').like(values['comment_object_id']))
        #         res_obj = self.page_query(_filter_obj, 'PT_Activity', page, count)
        #         if res_obj['result']:
        #             result['comment_object'] = '活动-'+ res_obj['result'][0].get('activity_name')
        #         else:
        #             res.get('result').pop(key)
        #             res['total'] =int(res.get('total')) - 1
        #     elif len(self.page_query(_filter_obj, 'PT_Comment', page, count)['result'])>0:
        #         res_obj = self.page_query(_filter_obj, 'PT_Comment', page, count)
        #         result['father_comment'] = '子评论-'+ res_obj['result'][0].get('content')
        return res

    def update_comment(self, comment):
        '''# 评论'''
        res = 'Fail'
        person_id = get_current_user_id(self.session)
        comment['comment_user_id'] = person_id
        comment['audit_status'] = 'auditing'
        comment['comment_date'] = datetime.datetime.now()
        if 'id' not in comment.keys():
            bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                        TypeId.comment.value, comment, 'PT_Comment')
            if bill_id:
                res = 'Success'
        return res

    def delete_comment(self, comment_ids):
        '''删除评论接口

        Arguments:
            comment_ids   {ids}      数据id
        '''
        res = 'fail'

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(comment_ids, str):
                ids.append(comment_ids)
            else:
                ids = comment_ids
            for comment_id in ids:
                # 查询被删除的数据信息
                data = find_data(db, 'PT_Comment', {
                    'id': comment_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.comment.value, data[0], 'PT_Comment')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name, process_func,self.db_user, self.db_pwd)
        return res

    def get_comment_audit_list(self, order_ids, condition, page, count):
        '''获取评论审核列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'comment_object_id', 'type_id', 'level',
                'comment_user_id', 'start_date', 'end_date']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()

        _filter.lookup_bill('PT_Comment_Type', 'type_id', 'id', 'type')\
            .add_fields({'type': '$type.name'})\
            .match_bill((C('audit_status') == 'audiing')
                        & C('organization_id').inner(order_ids)
                        & (C('comment_date') >= as_date(values['start_date']))
                        & (C('comment_date') <= as_date(values['end_date']))
                        & (C('id') == values['id'])
                        & (C('comment_object_id') == values['comment_object_id'])
                        & (C('type_id') == values['type_id'])
                        & (C('comment_user_id') == values['comment_user_id'])
                        & C('level').like(values['level']))\
            .project({'_id': 0, 'type._id': 0})
        res = self.page_query(_filter, 'PT_Comment', page, count)
        for key, result in enumerate(res.get('result')):
            comment_object_id = result.get('comment_object_id')
            _filter_obj = MongoBillFilter()
            _filter_obj.match((C('bill_status') == 'valid') & (
                C('id') == comment_object_id)).project({'_id': 0})
            if len(self.page_query(_filter_obj, 'PT_Service_Item', page, count)['result']) > 0:
                _filter_obj.match(C('name').like(values['comment_object_id']))
                res_obj = self.page_query(
                    _filter_obj, 'PT_Service_Item', page, count)
                if res_obj['result']:
                    result['comment_object'] = '服务项目-' + \
                        res_obj['result'][0].get('name')
                else:
                    res.get('result').pop(key)
                    res['total'] = int(res.get('total')) - 1
            elif len(self.page_query(_filter_obj, 'PT_Article', page, count)['result']) > 0:
                print('111', self.page_query(_filter_obj,
                                             'PT_Article', page, count)['result'])
                _filter_obj.match(C('title').like(values['comment_object_id']))
                res_obj = self.page_query(
                    _filter_obj, 'PT_Article', page, count)
                if res_obj['result']:
                    result['comment_object'] = '文章-' + \
                        res_obj['result'][0].get('title')
                else:
                    res.get('result').pop(key)
                    res['total'] = int(res.get('total')) - 1
            elif len(self.page_query(_filter_obj, 'PT_Activity', page, count)['result']) > 0:
                _filter_obj.match(C('activity_name').like(
                    values['comment_object_id']))
                res_obj = self.page_query(
                    _filter_obj, 'PT_Activity', page, count)
                if res_obj['result']:
                    result['comment_object'] = '活动-' + \
                        res_obj['result'][0].get('activity_name')
                else:
                    res.get('result').pop(key)
                    res['total'] = int(res.get('total')) - 1
            elif len(self.page_query(_filter_obj, 'PT_Comment', page, count)['result']) > 0:
                res_obj = self.page_query(
                    _filter_obj, 'PT_Comment', page, count)
                result['father_comment'] = '子评论-' + \
                    res_obj['result'][0].get('content')
        return res

    def comment_audit_success(self, comment):
        '''# 评论审核通过'''
        res = 'Fail'
        person_id = get_current_user_id(self.session)
        if comment['content']:
            comment.pop('content')
        else:
            pass
        comment['audit_user_id'] = person_id
        comment['audit_status'] = 'audit_success'
        comment['audit_date'] = datetime.datetime.now()
        bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                    TypeId.comment.value, comment, 'PT_Comment')
        if bill_id:
            res = 'Success'
        return res

    def comment_audit_fail(self, comment):
        '''# 评论审核不通过'''
        res = 'Fail'
        person_id = get_current_user_id(self.session)
        if comment['content']:
            comment.pop('content')
        else:
            pass
        comment['audit_user_id'] = person_id
        comment['audit_status'] = 'audit_fail'
        comment['audit_date'] = datetime.datetime.now()
        bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                    TypeId.comment.value, comment, 'PT_Comment')
        if bill_id:
            res = 'Success'
        return res
